package com.yc.http.tomcat.impl;

import com.yc.http.tomcat.Cookie;
import com.yc.http.tomcat.HttpServletRequest;
import com.yc.http.tomcat.HttpServletResponse;
import com.yc.http.tomcat.ServletException;

import java.io.IOException;
import java.io.PrintWriter;

public class CookieServlet extends HttpServletImpl{

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取浏览器发回给服务器的 cookie数据
        Cookie[] cookies = request.getCookies();
        // 输出cookie
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<ul>");
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                // a=100
                String s = cookie.getName() + " = " + cookie.getValue();
                out.println("<li>"+s+"</li>");
            }
        }
        out.println("</ul>");

        // 修改某个cookie值
        Cookie cookie = new CookieImpl("a","200");
        response.addCookie(cookie);

        // 删除cookie
        cookie = new CookieImpl("b","200");
        cookie.setMaxAge(0);// 设置有效期为 0 秒
        response.addCookie(cookie);

        // 添加新的cookie, 设定有效期 1 周
        String c = request.getParameter("c");
        cookie = new CookieImpl("c",c);
        cookie.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(cookie);

    }
}
